package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	businessResp "github.com/flipped-aurora/gin-vue-admin/server/model/business/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
)

type QuestionnaireApi struct {
}

var questionnaireService = service.ServiceGroupApp.BusinessServiceGroup.QuestionnaireService

// CreateQuestionnaire 创建问卷
// @Tags Questionnaire
// @Summary 创建问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Questionnaire true "创建问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /questionnaire/createQuestionnaire [post]
func (questionnaireApi *QuestionnaireApi) CreateQuestionnaire(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindJSON(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Name": {utils.NotEmpty()},
	}
	if err := utils.Verify(questionnaire, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		questionnaire.UserId = userId
	}
	if questionnaire.QuestionnaireType == 1 {
		err = questionnaireService.CreateQuestionnaireByEnterprise(&questionnaire)
		if err != nil {
			global.GVA_LOG.Error("创建问卷失败!", zap.Error(err))
			response.FailWithMessage("创建问卷失败", c)
			return
		}
	}
	response.OkWithMessage("创建成功", c)

}

// DeleteQuestionnaire 删除问卷
// @Tags Questionnaire
// @Summary 删除问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Questionnaire true "删除问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /questionnaire/deleteQuestionnaire [delete]
func (questionnaireApi *QuestionnaireApi) DeleteQuestionnaire(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindJSON(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	questionnaire.UserId = 0
	//当不是管理员时
	if isAdmin == 2 {
		questionnaire.UserId = utils.GetUserID(c)
	}
	if err := questionnaireService.DeleteQuestionnaire(questionnaire); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteQuestionnaireByIds 批量删除问卷
// @Tags Questionnaire
// @Summary 批量删除问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /questionnaire/deleteQuestionnaireByIds [delete]
func (questionnaireApi *QuestionnaireApi) DeleteQuestionnaireByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := uint(0)
	//当不是管理员时
	if isAdmin == 2 {
		userId = utils.GetUserID(c)
	}
	if err := questionnaireService.DeleteQuestionnaireByIds(IDS, userId); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateQuestionnaire 更新问卷
// @Tags Questionnaire
// @Summary 更新问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Questionnaire true "更新问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /questionnaire/updateQuestionnaire [put]
func (questionnaireApi *QuestionnaireApi) UpdateQuestionnaire(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindJSON(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Name": {utils.NotEmpty()},
	}
	if err := utils.Verify(questionnaire, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	//当不是管理员时
	if isAdmin == 2 {
		questionnaire.UserId = utils.GetUserID(c)
	}
	if err := questionnaireService.UpdateQuestionnaire(questionnaire); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindQuestionnaire 用id查询问卷
// @Tags Questionnaire
// @Summary 用id查询问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query business.Questionnaire true "用id查询问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /questionnaire/findQuestionnaire [get]
func (questionnaireApi *QuestionnaireApi) FindQuestionnaire(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindQuery(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)

	//当不是管理员时
	if isAdmin == 2 {
		questionnaire.UserId = utils.GetUserID(c)
	}
	if requestionnaire, err := questionnaireService.GetQuestionnaire(questionnaire.ID, questionnaire.UserId); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"requestionnaire": requestionnaire}, c)
	}
}

// FindQuestionnaireByUuid 用uuid查询问卷
// @Tags Questionnaire
// @Summary 用id查询问卷
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query business.Questionnaire true "用id查询问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /questionnaire/findQuestionnaireByUuid [get]
func (questionnaireApi *QuestionnaireApi) FindQuestionnaireByUuid(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindQuery(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := uint(0)
	//当不是管理员时
	if isAdmin == 2 {
		userId = utils.GetUserID(c)
	}
	if requestionnaire, err := questionnaireService.GetQuestionnaireByUuid(questionnaire.Uuid, userId); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"requestionnaire": requestionnaire}, c)
	}
}

// GetQuestionnaireList 分页获取问卷列表
// @Tags Questionnaire
// @Summary 分页获取问卷列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.QuestionnaireSearch true "分页获取问卷列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /questionnaire/getQuestionnaireList [get]
func (questionnaireApi *QuestionnaireApi) GetQuestionnaireList(c *gin.Context) {
	var pageInfo businessReq.QuestionnaireSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		pageInfo.UserId = userId
	}
	if list, total, err := questionnaireService.GetQuestionnaireInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// 获取问卷详细题目内容
func (questionnaireApi *QuestionnaireApi) GetQuestionnaireInfo(c *gin.Context) {
	var questionnaire business.Questionnaire
	err := c.ShouldBindQuery(&questionnaire)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := uint(0)
	//当不是管理员时
	if isAdmin == 2 {
		userId = utils.GetUserID(c)
	}
	requestionnaire, err := questionnaireService.GetQuestionnaireByUuid(questionnaire.Uuid, userId)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if requestionnaire.ID == 0 {
		response.FailWithMessage("没有该问卷", c)
		return
	}
	//获取题目信息
	questionList, err := questionService.GetQuestionInfoListByQuestionnaire(questionnaire.Uuid)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	//获取题目选项
	optionList, err := optionService.GetOptionInfoListByQuestionnaire(questionnaire.Uuid)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	//定义个Map
	optionListMap := make(map[int32][]*business.Option)
	for k, v := range optionList {
		optionListMap[v.QuestionSort] = append(optionListMap[v.QuestionSort], &optionList[k])
	}
	//定义返回值
	var result businessResp.QuestionnaireInfo
	err = copier.Copy(&result, &requestionnaire)
	if err != nil {
		response.FailWithMessage("问卷发生错误", c)
		return
	}
	var questionnaireQuestion []*businessResp.QuestionnaireQuestion
	err = copier.Copy(&questionnaireQuestion, &questionList)
	if err != nil {
		response.FailWithMessage("问卷发生错误", c)
		return
	}
	for k, v := range questionnaireQuestion {
		questionnaireQuestion[k].List = optionListMap[v.Sort]
	}
	result.List = questionnaireQuestion
	response.OkWithData(gin.H{"questionnaireInfo": result, "total": len(questionnaireQuestion)}, c)

}
